<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<%@ taglib prefix="fn"  uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page import="kr.co.insoft.framework.config.Authorities" %>
<c:set var="CONTEXT">${pageContext.request.contextPath}</c:set>
<c:set var="cssUrl">${pageContext.request.contextPath}/resources/css</c:set>
<c:set var="imgUrl">${pageContext.request.contextPath}/resources/images</c:set>
<c:set var="jsUrl">${pageContext.request.contextPath}/resources/js</c:set>
<link rel="stylesheet" type="text/css" href="${cssUrl }/skin/ui.dynatree.css" >
<script type="text/javascript" src="${jsUrl }/jquery-ui.min.js"></script>
<script type="text/javascript" src="${jsUrl }/jquery.cookie.js"></script>
<script type="text/javascript" src="${jsUrl }/jquery.dynatree.js"></script>
<script type="text/javascript" src="${jsUrl}/contextmenu/jquery.contextMenu-custom.js"></script>
<link rel="stylesheet" type="text/css" href="${jsUrl}/contextmenu/jquery.contextMenu.css" />
<div class="col-sm-12" id="orchestrationMainBody">
	<div class="col-sm-3 treeZone animateObject1">
		<div class="btn-group bottommargin10">
			<c:if test="${fn:contains(buttons , Authorities.CREATE)}">
			<button type="button" class="btn btn-default btnCreateProject">Project 생성</button>
			</c:if>
			<button type="button" class="btn btn-default btnTreeReload"><i class="fa fa-refresh"></i></button>
			<c:if test="${fn:contains(buttons , Authorities.CREATE)}"></c:if>
		</div>
		<div id="categoryTreeZone"></div>
	</div>
	<div class="col-sm-9 animateObject1 animateObject2" id="nodeDataZone">
		<div id="contentZone"></div>
	</div>
	<div id="additionalContentZone" class="animateObject2"></div>
</div>


<%-- Hidden --%>
<ul id="TCMROOT" class="contextMenu">
<li><a href="#">My Orchestration</a>
<li class="separator"><a href="#createProject"><i class="fa fa-plus">&nbsp;&nbsp;</i>Create Project</a>
</ul>
<ul id="TCMproject" class="contextMenu">
<li><a href="#">Project</a>
<li class="separator"><a href="#createProject"><i class="fa fa-pencil">&nbsp;&nbsp;</i>Create Project</a></li>
<li><a href="#editProject"><i class="fa fa-edit">&nbsp;&nbsp;</i>Edit Project</a></li>
<li><a href="#removeProject"><i class="fa fa-trash-o">&nbsp;&nbsp;</i>Delete Project</a></li>
<li class="separator"><a href="#createService"><i class="fa fa-pencil">&nbsp;&nbsp;</i>Create Child Service</a>
</ul>
<ul id="TCMservice" class="contextMenu">
<li><a href="#">Service</a>
<li class="separator"><a href="#createService"><i class="fa fa-pencil">&nbsp;&nbsp;</i>Create Service</a></li>
<li><a href="#editService"><i class="fa fa-edit">&nbsp;&nbsp;</i>Edit Service</a></li>
<li><a href="#removeService"><i class="fa fa-trash-o">&nbsp;&nbsp;</i>Delete Service</a></li>
<li class="separator"><a href="#createComposite"><i class="fa fa-pencil">&nbsp;&nbsp;</i>Create Child VM Composite</a>
</ul>
<ul id="TCMvmcomposite" class="contextMenu">
<li><a href="#">VM Composite</a>
<li class="separator"><a href="#createComposite"><i class="fa fa-pencil">&nbsp;&nbsp;</i>Create VM Composite</a></li>
<li><a href="#editComposite"><i class="fa fa-edit">&nbsp;&nbsp;</i>Edit VM Composite</a></li>
<li><a href="#removeComposite"><i class="fa fa-trash-o">&nbsp;&nbsp;</i>Delete VM Composite</a></li>
<li class="separator"><a href="#createStack"><i class="fa fa-pencil">&nbsp;&nbsp;</i>Create VM Composite Stack</a>
<li class="separator"><a href="#listEventChain"><i class="fa fa-link">&nbsp;&nbsp;</i>Event Chain</a>
<li><a href="#listApplication"><i class="fa fa-font">&nbsp;&nbsp;</i>Application</a>
</ul>
<ul id="TCMvmcompositestack" class="contextMenu">
<li><a href="#">VM Composite Stack</a>
<li class="separator"><a href="#createStack"><i class="fa fa-pencil">&nbsp;&nbsp;</i>Create VM Composite Stack</a></li>
<li><a href="#editStack"><i class="fa fa-edit">&nbsp;&nbsp;</i>Edit VM Composite Stack</a></li>
<li><a href="#removeStack"><i class="fa fa-trash-o">&nbsp;&nbsp;</i>Delete VM Composite Stack</a></li>
<li class="separator"><a href="#scaleoutStack"><i class="fa fa-plus">&nbsp;&nbsp;</i>Scale Out</a>
<li><a href="#scaleinStack"><i class="fa fa-minus">&nbsp;&nbsp;</i>Scale In</a>
</ul>
<ul id="TCMha" class="contextMenu">
<li><a href="#">HA</a>
<li class="separator"><a href="#scaleoutHa"><i class="fa fa-plus">&nbsp;&nbsp;</i>Scale Out</a></li>
<li><a href="#scaleinHa"><i class="fa fa-minus">&nbsp;&nbsp;</i>Scale In</a>
</ul>
<ul id="TCMinstance" class="contextMenu">
<li><a href="#create">INSTANCE</a>
<li class="separator"><a href="#scaleoutInstance"><i class="fa fa-plus">&nbsp;&nbsp;</i>Scale Out</a></li>
<li><a href="#scaleinInstance"><i class="fa fa-minus">&nbsp;&nbsp;</i>Scale In</a>
</ul>
<script type="text/javascript"><!--
function callingForm(formType, types, targetid) {
	Loading.show();
	$("#contentZone").fadeOut(500, function() {
		var url = "${CONTEXT}/orchestration/orchestration/callForm";
		var param = {"formType" : formType, "types" : types, "targetid" : targetid};
		$.post(url, param, function(res) {
			$("#contentZone").html(res);
			$("#contentZone").fadeIn(500);
		}).fail(function() {
			bootbox.alert("사용시간이 만료되었습니다. 페이지를 리로딩합니다.", function() {
				location.reload();
			});
		}).always(function() {
			Loading.hide();
		});		
	});
}

function bindContextMenu(types, span) {
	$(span).contextMenu({menu: "TCM"+types}, function(action, el, pos) {
		var node = $.ui.dynatree.getNode(el);
		console.log("metadata", node.data.metadata);
		switch( action ) {
		case "createProject":
			callingForm("create", "project", node.data.metadata.child_uid);
			break;
		case "createService":
			callingForm("create", "service", node.data.metadata.child_uid);
			break;
		case "createComposite":
			callingForm("create", "vmcomposite", node.data.metadata.child_uid);
			break;
		case "createStack":
			callingForm("create", "vmcompositestack", node.data.metadata.child_uid);
			break;
		case "editProject":
			callingForm("edit", "project", node.data.metadata.child_uid);
			break;
		case "editService":
			callingForm("edit", "service", node.data.metadata.child_uid);
			break;
		case "editComposite":
			callingForm("edit", "vmcomposite", node.data.metadata.child_uid);
			break;
		case "editStack":
			callingForm("edit", "vmcompositestack", node.data.metadata.child_uid);
			break;
		case "removeProject":
			bootbox.confirm("<spring:message code='common.remove.confirm'/>", function(result) {
				if (result) {
					Loading.show();
					$.post("./removeProject", {"targetid" : node.data.metadata.child_uid}, function(res) {
						console.log(res);
					}).done(function(res){
						if (res)
							bootbox.alert("<spring:message code='common.remove.ok'/>");
						else
							bootbox.alert("<spring:message code='common.remove.have.child.service'/>");
					}).fail(function(){
						bootbox.alert("<spring:message code='common.server.fail'/>");
					}).always(function(){
						doTreeReload();
						Loading.hide();
					});
				}
			});
			break;
		case "removeService":
			bootbox.confirm("<spring:message code='common.remove.confirm'/>", function(result) {
				if (result) {
					Loading.show();
					$.post("./removeService", {"targetid" : node.data.metadata.child_uid}, function(res) {
						console.log(res);
					}).done(function(res){
						if (res)
							bootbox.alert("<spring:message code='common.remove.ok'/>");
						else
							bootbox.alert("<spring:message code='common.remove.have.child.service'/>");
					}).fail(function(){
						bootbox.alert("<spring:message code='common.server.fail'/>");
					}).always(function(){
						doTreeReload();
						Loading.hide();
					});
				}
			});
		case "removeComposite":
			bootbox.confirm("<spring:message code='common.remove.confirm'/>", function(result) {
				if (result) {
					Loading.show();
					$.post("./removeComposite", {"targetid" : node.data.metadata.child_uid}, function(res) {
						console.log(res);
					}).done(function(res){
						if (res)
							bootbox.alert("<spring:message code='common.remove.ok'/>");
						else
							bootbox.alert("<spring:message code='common.remove.have.child.service'/>");
					}).fail(function(){
						bootbox.alert("<spring:message code='common.server.fail'/>");
					}).always(function(){
						doTreeReload();
						Loading.hide();
					});
				}
			});
		case "removeStack":
		case "scaleoutStack":
		case "scaleoutHa":
		case "scaleoutInstance":
		case "scaleinStack":
		case "scaleinHa":
		case "scaleinInstance":
			break;
		default:
			break;
		}
	});
};

function doTreeReload() {
	var tree = $("#categoryTreeZone").dynatree("getTree");
	tree.reload();
}

$(document).ready(function() {
	$("#contentZone").hide();
	$("#additionalContentZone").hide();
	$("#categoryTreeZone").dynatree({
		debugLevel : 0,
		persist: true,
		fx: { height: "toggle", duration: 200 },
		autoFocus: true,
		initAjax : {
			url: "${CONTEXT}/rest/orchestration/orchestration/getTreeNonRoot.json"
		},
		onPostInit : function(isReloading, isError) {
			this.reactivate();
		},
		onCreate: function(node, span){
			if ( node.data.metadata ) {
				var types = 'ROOT';
				if ( node.data.metadata.types ) {
					types = node.data.metadata.types;
				}
				bindContextMenu(types, span);
			}
	      },
		onClick: function(node, event) {
	        if( $(".contextMenu:visible").length > 0 ){
	          $(".contextMenu").hide();
	        }
	      },
		onActivate : function(node) {
			node.toggleSelect();
		},
		onSelect: function(select, node) {
			var selKeys = $.map(node.tree.getSelectedNodes(), function(node){
				return node.data.child_uid;
			});
			
			//selectedItem = [];
			$.map(node.tree.getSelectedNodes(), function(node){
				//selectedItem.push(node.data.metadata);
			});
			var selRootNodes = node.tree.getSelectedNodes(true);
			var selRootKeys = $.map(selRootNodes, function(node){
				return node.data.child_uid;
			});
		},
		onDblClick: function(node, event) {
			//node.toggleSelect();
			if ( node.data.metadata.types ) {
				console.log("metadata", node.data.metadata);
				callingForm("view", node.data.metadata.types, node.data.metadata.child_uid);
			}
		},
		onKeydown: function(node, event) {
			if( $(".contextMenu:visible").length > 0 )
		          return false;
			
			switch( event.which ) {
	        case 32: // [Space]
	          $(node.span).trigger("mousedown", {
	            preventDefault: true,
	            button: 2
	            })
	          .trigger("mouseup", {
	            preventDefault: true,
	            pageX: node.span.offsetLeft,
	            pageY: node.span.offsetTop,
	            button: 2
	            });
	          return false;
	        }
		}
	});
	
	$(document).on("click", ".btnCreateProject", function() {
		callingForm("create", "project", 0);
	}).on("click",".btnCreateTarget", function() {
		var node = $("#categoryTreeZone").dynatree("getActiveNode");
		console.log("create Target", node);
	}).on("click",".btnEditTarget", function() {
		var node = $("#categoryTreeZone").dynatree("getActiveNode");
		console.log("edit Target", node);
	}).on("click",".btnRemoveTarget", function() {
		var node = $("#categoryTreeZone").dynatree("getActiveNode");
		console.log("remove Target", node);
	}).on("click",".btnTreeReload", function() {
		doTreeReload();
	}).on("click", ".btnSubPageRevertMainView", function() {
		$(".animateObject2").fadeOut(500, function() {
			$("#nodeDataZone").removeClass("col-sm-6").addClass("col-sm-8");
			$(".animateObject1").fadeIn(500);
		});
	}).on("click", ".btnSubPageAddVariable", function() {
		Loading.show();
		$.get("${CONTEXT}/configration/sev/lists", {"ip":"Y"}, function(result) {
			$("#additionalContentZone").addClass("col-sm-6").html(result);
		}).fail(function() {
			$(".animateObject2").fadeOut(500, function() {
				$("#nodeDataZone").removeClass("col-sm-6").addClass("col-sm-8");
				$(".animateObject1").fadeIn(500);
			});
		}).done(function(result) {
			$(".animateObject1").fadeOut(function(){
				$("#nodeDataZone").removeClass("col-sm-8").addClass("col-sm-6");
				$(".animateObject2").fadeIn(500);				
			});
		}).always(function() {
			Loading.hide();	
		});
	}).on("click", ".removePageVariable", function() {
		$("#"+$(this).data("target")).remove();
	}).on("click", ".btnVaraibleSelected", function() {
		var isDuplicate = true;
		var targetVariableId = $(this).data("variableid");
		$.each($(":input[name='variable']"), function() {
			if ( $(this).val() ==  targetVariableId) {
				isDuplicate = false;
				return;
			}
		});
		if (isDuplicate) {
			var param = {"variableid" : $(this).data("variableid")};
			$.get("${CONTEXT}/configration/sev/simpleView", param, function(resultVariableHtml) {
				$("#variablesArea").append(resultVariableHtml);	
			});			
		} else {
			bootbox.alert("<spring:message code='common.variable.is.exist'/>");	
		}
	}).on("click",".btnSubPageCreate", function() {
		var button = $(this);
		bootbox.confirm("<spring:message code='common.save.confirm'/>", function(result) {
			if ( result ) {
				Loading.show();
				var variables = [];
				$.each($(":input[name='variable']"), function(index, item) {
					variables.push($(this).val());
				});
				$("#variableTemp").val(variables.join(","));
				
				var types = button.data("types");
				var url = "";
				var target = "";
				switch(types) {
				case "project":
					url = "${CONTEXT}/orchestration/orchestration/createProject.json";
					target = $("#projectEntityModel").serialize();
					break;
				case "service":
					url = "${CONTEXT}/orchestration/orchestration/createService.json";
					target = $("#serviceEntityModel").serialize();
					break;
				case "vmcomposite":
					url = "${CONTEXT}/orchestration/orchestration/createComposite.json";
					target = $("#compositeEntityModel").serialize();
					break;
				case "vmcompositestack":
					url = "${CONTEXT}/orchestration/orchestration/createStack.json";
					$("#hardwareProfileName").val($("#hardwareProfileId option:selected").val());
					$("#imageName").val($("#imageId option:selected").val());
					target = $("#compositeStackEntityModel").serialize();
					break;
				default:
					break;
				}
				
				$.post(url, target, function(createResult) {
				}).fail(function(createResult){
					bootbox.alert("<spring:message code='common.server.fail'/>");
				}).done(function(createResult){
					if (createResult.orchestrationResultModel.result) {
						bootbox.alert("<spring:message code='common.save.ok'/>", function() {
							callingForm("view", createResult.orchestrationResultModel.types, createResult.orchestrationResultModel.id);							
						});
					} else {
						bootbox.alert("<spring:message code='common.save.fail'/>");
					}
				}).always(function() {
					doTreeReload();
					$(".animateObject2").fadeOut(500, function() {
						$("#nodeDataZone").removeClass("col-sm-6").addClass("col-sm-8");
						$(".animateObject1").fadeIn(500);
					});
					Loading.hide();
				});
			}
		});
	}).on("change",".connectionSelect", function() {
		var connectionid = $(this).find("option:selected").val();
		var param = {"connectionid" : connectionid};
		if ( connectionid != "" ) {
			Loading.show();
			$.get("${CONTEXT}/rest/driver/api/getHardwareProfiles.json", param, function(hardwareResult) {
				var opt = "";
				$.each(hardwareResult, function(index, item){
					opt += "<option value='"+item.id+"'>"+item.name+"</option>";
				});
				$("#hardwareProfileId").append(opt);
			}).done(function() {
				$.get("${CONTEXT}/rest/driver/api/getMyImages.json", param, function(imagesResult) {
					var opt = "";
					$.each(imagesResult, function(index, item){
						opt += "<option value='"+item.imageId+"'>"+item.name+"</option>";
					});
					$("#imageId").append(opt);
				});
			}).always(function() {
				Loading.hide();
			});
		}
	});
});
//--></script>